(function($) {
var olderPostsLink = '';
var postContainerSelector = '#Blog1';
var loading = false;

var win = $(window);
var doc = $('#Blog1');

function loadMore() {
  if (loading) {
    return;
  }
  loading = true;
  if (!olderPostsLink) {
    return;
  }
  $.ajax(olderPostsLink, {
    'dataType': 'html'
  }).done(function(html) {
    var newDom = $('<div></div>').append(html);
    var newLink = newDom.find('a.blog-pager-older-link');
    if (newLink) {
      olderPostsLink = newLink.attr('href');
    } else {
      olderPostsLink = '';
    }

    var newPosts = newDom.find(postContainerSelector).children().not('#blog-pager');
    $(postContainerSelector).append(newPosts);
    loading = false;
  });
}

function getDocumentHeight() {
  return Math.max(
      win.height(),
      doc.height(),
      document.documentElement.clientHeight);
}

function handleScroll() {
  var height = getDocumentHeight();
  var pos = win.scrollTop() + win.height();
  if (height - pos < 150) {
    loadMore();
  }
}

function init() {
  olderPostsLink = $('a.blog-pager-older-link').attr('href');
  if (!olderPostsLink) {
    return;
  }
  win.scroll(handleScroll);
  $('#blog-pager').hide();
}
$(document).ready(init);
})(jQuery);
